﻿using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace QQ2564874169.Core.Encryption
{
    public static class Decrypt
    {
        public static string DES(string content, string salt)
        {
            if (string.IsNullOrEmpty(salt) || salt.Length != 8)
                throw new ArgumentException("salt的长度必须是8位。");
            var sinput = content.Split("-".ToCharArray());
            var data = new byte[sinput.Length];
            for (var i = 0; i < sinput.Length; i++)
            {
                data[i] = byte.Parse(sinput[i], NumberStyles.HexNumber);
            }
            var key = Encoding.ASCII.GetBytes(salt);
            var iv = Encoding.ASCII.GetBytes(salt);
            using (var des = new DESCryptoServiceProvider {Key = key, IV = iv})
            {
                var desencrypt = des.CreateDecryptor();
                var result = desencrypt.TransformFinalBlock(data, 0, data.Length);
                return Encoding.UTF8.GetString(result);
            }
        }

        public static string RSA(string content, string privatekey)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privatekey);
                var cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
                return Encoding.UTF8.GetString(cipherbytes);
            }
        }

        public static string TripleDES(string key, string content, Encoding encoding = null)
        {
            if (string.IsNullOrEmpty(content))
                throw new ArgumentNullException("content");
            encoding = encoding ?? Encoding.UTF8;
            var des = new TripleDESCryptoServiceProvider
            {
                Key = Encoding.ASCII.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            var decr = des.CreateDecryptor();
            var data = Convert.FromBase64String(content);
            return encoding.GetString(decr.TransformFinalBlock(data, 0, data.Length));
        }
    }
}
